package cz.mff.curreco.utils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;

import cz.mff.curreco.model.Circle;

public class ImageUtils {
	public static int createRGBColor(int red, int green, int blue) {
		return 0xFF000000| red<<16|green<<8|blue;
	}
	
	public static int getAvg(int color) {
		int red = (color & 0x00ff0000)  >> 16;
		int green = (color & 0x0000ff00)  >> 8;
		int blue = (color & 0x000000ff)  >> 0;
		return (red+green+blue)/3;
	}
	
	public static BufferedImage resizeImage(BufferedImage bi, double ratio) {
		System.out.println("Ratio: " + ratio);
		int width = (int)(bi.getWidth()*ratio);
		int height = (int)(bi.getHeight()*ratio);
		BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(bi, 0, 0, width, height, null);
		g.dispose();
		return resizedImage;
	}
	
	public static int getRGB(BufferedImage img, int x, int y)
	{
		return img.getRGB(x, y)& 0x00FFFFFF;
		
	}
	
	public static BufferedImage cloneImage(BufferedImage source)
	{
		 ColorModel cm = source.getColorModel();
		 //boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
		 WritableRaster raster = source.copyData(null);

		 BufferedImage resulImage = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
		 resulImage.setData(raster);
		 return resulImage;
	}
	
	public static BufferedImage cropImage(BufferedImage image, Circle coin) {
		int width = coin.getDiameter()+10;
		int height = coin.getDiameter()+10;
		System.out.println("DIAMETER: "+coin.getDiameter());
		System.out.println("CROP TO: "+width+"x"+height);
		int leftTopX = coin.getCenterX()-(width/2)-5 ;
		int leftTopY = coin.getCenterY()-(height/2)-5;
		System.out.println("LEFT TOP: ["+leftTopX+", "+leftTopY+"]");
		BufferedImage cropedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		Graphics2D g = (Graphics2D) cropedImage.getGraphics().create();  
		g.drawImage(image, 0, 0, cropedImage.getWidth(), cropedImage.getHeight(), leftTopX, leftTopY, leftTopX + cropedImage.getWidth(), leftTopY + cropedImage.getHeight(), null);
		g.dispose();
		return cropedImage;
	}
}
